<template>
  <page-container :title="$route.meta.title">
    <search-form :model="searchForm" @search="handleSearch" @reset="handleReset">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="任务名称" prop="jobName">
            <el-input v-model="searchForm.jobName" placeholder="请输入任务名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="任务组名" prop="jobGroup">
            <el-input v-model="searchForm.jobGroup" placeholder="请输入任务组名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="执行状态" prop="status">
            <el-select v-model="searchForm.status" placeholder="请选择状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="成功" value="1"></el-option>
              <el-option label="失败" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="执行时间" prop="dateRange">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="search-buttons">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button 
            type="danger" 
            icon="el-icon-delete" 
            @click="handleCleanLog"
            v-permission="'job:log:clean'"
          >
            清空日志
          </el-button>
        </el-col>
      </el-row>
    </search-form>

    <div class="table-container">
      <el-table
        :data="logList"
        border
        stripe
        style="width: 100%;"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="jobName" label="任务名称" min-width="150"></el-table-column>
        <el-table-column prop="jobGroup" label="任务组名" min-width="120"></el-table-column>
        <el-table-column prop="executeTime" label="执行时间" min-width="160" :formatter="formatDate"></el-table-column>
        <el-table-column prop="executeDuration" label="执行耗时(ms)" min-width="120">
          <template slot-scope="scope">
            <span :class="scope.row.executeDuration > 1000 ? 'text-warning' : ''">
              {{ scope.row.executeDuration }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="执行状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="text" 
              @click="handleViewLog(scope.row)"
              v-permission="'job:log:view'"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page="pagination.pageNum"
        :page-size="pagination.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 15px; text-align: right;"
      ></el-pagination>
    </div>
  </page-container>

  <!-- 日志详情弹窗 -->
  <el-dialog
    title="日志详情"
    :visible.sync="logDetailVisible"
    width="80%"
    :modal-append-to-body="false"
    :append-to-body="true"
  >
    <el-descriptions column="1" border>
      <el-descriptions-item label="任务名称">{{ currentLog.jobName }}</el-descriptions-item>
      <el-descriptions-item label="任务组名">{{ currentLog.jobGroup }}</el-descriptions-item>
      <el-descriptions-item label="执行时间">{{ formatDate(currentLog.executeTime) }}</el-descriptions-item>
      <el-descriptions-item label="执行耗时">{{ currentLog.executeDuration }} 毫秒</el-descriptions-item>
      <el-descriptions-item label="执行状态">
        <el-tag :type="currentLog.status === 1 ? 'success' : 'danger'">
          {{ currentLog.status === 1 ? '成功' : '失败' }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="任务参数">{{ currentLog.parameter || '无' }}</el-descriptions-item>
      <el-descriptions-item label="执行类路径">{{ currentLog.jobClassPath }}</el-descriptions-item>
      <el-descriptions-item label="错误信息" v-if="currentLog.status === 0">
        <div class="error-message">{{ currentLog.errorMsg }}</div>
      </el-descriptions-item>
    </el-descriptions>
    <div slot="footer" class="dialog-footer">
      <el-button @click="logDetailVisible = false">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { getJobLogDetail } from '@/api/log'
import PageContainer from '@/components/common/PageContainer.vue'
import SearchForm from '@/components/common/SearchForm.vue'

export default {
  name: 'JobLog',
  components: {
    PageContainer,
    SearchForm
  },
  data() {
    return {
      searchForm: {
        jobName: '',
        jobGroup: '',
        status: '',
        dateRange: []
      },
      pagination: {
        pageNum: 1,
        pageSize: 10
      },
      loading: false,
      logDetailVisible: false,
      currentLog: {}
    }
  },
  computed: {
    ...mapState({
      logList: state => state.log.logList,
      total: state => state.log.total
    })
  },
  methods: {
    ...mapActions({
      getJobLogList: 'log/getJobLogList',
      cleanJobLog: 'log/cleanJobLog'
    }),
    
    // 格式化日期
    formatDate(value) {
      return this.$options.filters.formatDate(value)
    },
    
    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1
      this.loadLogList()
    },
    
    // 重置
    handleReset() {
      this.searchForm = {
        jobName: '',
        jobGroup: '',
        status: '',
        dateRange: []
      }
      this.pagination.pageNum = 1
      this.loadLogList()
    },
    
    // 加载日志列表
    loadLogList() {
      this.loading = true
      const params = {
        ...this.searchForm,
        ...this.pagination,
        startTime: this.searchForm.dateRange[0] || '',
        endTime: this.searchForm.dateRange[1] || ''
      }
      // 删除dateRange，避免传给后端
      delete params.dateRange
      
      this.getJobLogList(params).finally(() => {
        this.loading = false
      })
    },
    
    // 查看日志详情
    handleViewLog(row) {
      getJobLogDetail(row.id).then(response => {
        this.currentLog = response.data
        this.logDetailVisible = true
      })
    },
    
    // 清空日志
    handleCleanLog() {
      this.$confirm('确定要清空所有任务执行日志吗？此操作不可恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.cleanJobLog({
          jobName: this.searchForm.jobName,
          jobGroup: this.searchForm.jobGroup
        }).then(() => {
          this.$message.success('日志清空成功')
          this.loadLogList()
        })
      })
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadLogList()
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.loadLogList()
    }
  },
  created() {
    this.loadLogList()
  }
}
</script>

<style scoped>
.table-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-buttons {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
  padding-top: 10px;
}

.text-warning {
  color: #e6a23c;
}

.error-message {
  background-color: #fef0f0;
  border: 1px solid #fde2e2;
  border-radius: 4px;
  padding: 10px;
  color: #f56c6c;
  font-family: monospace;
  white-space: pre-wrap;
  max-height: 300px;
  overflow-y: auto;
}
</style>
